<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{
        goodsId ? "修改商品" : "添加商品"
      }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        :title="goodsId ? '修改商品信息' : '添加商品信息'"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tab栏 -->
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTaleData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  :key="i"
                  v-for="(cb, i) in item.attr_vals"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :label="item.attr_name"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button
              type="primary"
              class="btnAdd"
              @click="add"
              v-show="this.goodsId ? false : true"
              >添加商品</el-button
            >
            <!-- 修改商品的按钮 -->
            <el-button
              type="primary"
              class="btnEdit"
              @click="editGoodInfo"
              v-show="this.goodsId ? true : false"
              >提交修改</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览图片的对话框 -->
      <el-dialog title="预览图片" :visible.sync="previewVisible" width="50%">
        <img :src="previewPath" class="preview_pic" />
      </el-dialog>
    </el-card>
  </div>
</template>

 <script>
import _ from "lodash";

export default {
  name: "Add",
  data() {
    return {
      activeIndex: "0",
      // 表单数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        goods_introduce: "",
        attrs: [],
      },
      // 校验 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 商品分类数据
      cateList: [],
      // 商品分类的配置
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 参数列表数据
      manyTaleData: [],
      // 静态属性列表
      onlyTableData: [],
      // 图片上传的服务器地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 上传图片的请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片的src
      previewPath: "",
      // 控制预览图片的对话框
      previewVisible: false,
      // 商品列表传过来的goodsId
      goodsId: "",
      // 图片列表
      fileList: [],
    };
  },

  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },

  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.cateList = res.data;
    },

    // 商品分类选择器变化触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },

    // tab栏发生切换
    beforeTabLeave(activeNmae, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },

    // 点击tab栏触发
    async tabClicked() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取参数列表失败");
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTaleData = res.data;
      }

      if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取属性列表失败");
        this.onlyTableData = res.data;
      }
    },

    // 预览图片触发的事件
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },

    // 删除图片触发的事件
    handleRemove(file) {
      console.log(file);
      const filePath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex((x) => x.pic === filePath);
      this.addForm.pics.splice(i, 1);
    },

    // 图片上传成功触发
    handleSuccess(response) {
      console.log(response);
      const picInfo = {
        pic: response.data.tmp_path,
      };
      if (this.addForm.hasOwnProperty("pics")) {
        this.addForm.pics.push(picInfo);
      }else{
        this.addForm.pics = [];
        this.addForm.pics.push(picInfo);
      }
    },

    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项");
        // 深拷贝addform
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // 处理动态参数
        this.manyTaleData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;
        // 发起请求
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },

    // 根据id查询商品
    async getGoodsById() {
      const { data: res } = await this.$http.get(`goods/${this.goodsId}`);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品信息失败");
      // 将数据复制给表单
      this.addForm.goods_name = res.data.goods_name;
      this.addForm.goods_price = res.data.goods_price;
      this.addForm.goods_weight = res.data.goods_weight;
      this.addForm.goods_number = res.data.goods_number;
      res.data.goods_cat = res.data.goods_cat.split(",");
      this.addForm.goods_cat = res.data.goods_cat;
      // res.data.attrs.forEach((item) => {
      //   if (item.attr_sel == "only") {
      //     this.onlyTableData.push(item);
      //   } else {
      //     item.attr_vals = item.attr_vals.split(" ");
      //     this.manyTaleData.push(item);
      //   }
      // });
      // 将图片展示出来
      res.data.pics.forEach((item) => {
        let picObj = {
          url: item.pics_mid_url,
        };
        this.fileList.push(picObj);
      });
      this.addForm.goods_introduce = res.data.goods_introduce;
      console.log("根据id获取商品的信息：");
      console.log(res);
    },

    // 修改商品信息
    async editGoodInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项");
        // 深拷贝addform
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // 处理动态参数
        this.manyTaleData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;
        console.log(form);
        // 发起请求
        const { data: res } = await this.$http.put(
          `goods/${this.goodsId}`,
          form
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success("商品信息修改成功");
        this.$router.push("/goods");
      });
    },
  },

  created() {
    this.getCateList();
    this.goodsId = this.$route.query.goodsId;
    if (this.goodsId) {
      this.getGoodsById();
    }
  },
};
</script>

<style lang='less' scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.preview_pic {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}

.btnEdit {
  margin-top: 15px;
}
</style>